package de.bib.blue.manage.finance.dialog;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;

import de.bib.blue.manage.finance.util.UIHelper;

public class LoginDialog extends AbstractUserDialog {

	/**
	 * Tinggi form.
	 */
	private static final int HEIGHT = 140;

	/**
	 * Tinggi form.
	 */
	private static final int WIDTH = 240;

	/**
	 * Margin login container.
	 */
	private static final int MARGIN = 24;

	/**
	 * Exception dari login terakhir.
	 */
	private final Exception lastException;

	/**
	 * Jumlah percobaan login.
	 */
	private final int attempts;

	/**
	 * Dibuat harus dengan sebuah sheel tempat dialog di buka.
	 * 
	 * @param shell
	 *            sheel tempat dialog di buka.
	 * @param lastException
	 *            exception dari login terakhir
	 * @param attempts
	 *            jumlah percobaan login.
	 */
	public LoginDialog(Shell shell, Exception lastException, int attempts) {
		super(shell, "Login Form");
		this.lastException = lastException;
		this.attempts = attempts;
	}

	@Override
	protected Control createContents(Composite parent) {
		Control contents = createNewContents(parent,
				"Please specify username and password");

		if (lastException != null) {
			if (lastException.getMessage() != null) {
				setErrorMessage(lastException.getMessage());
			} else {
				if (attempts > 0) {
					setErrorMessage("Username or password in correct");
				}
			}
		} else {
			setErrorMessage(null);
		}

		return contents;
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		Composite composite = new Composite(parent, SWT.NONE);
		composite.setLayoutData(UIHelper.fillBoth());
		composite.setLayout(UIHelper.createNoMarginSpaceGridLayout());
		UIHelper.separator(composite, SWT.HORIZONTAL);

		/**
		 * Penampung label dan text username/password
		 */
		Composite container = new Composite(composite, SWT.NONE);
		GridLayout gridLayout = new GridLayout(2, false);
		gridLayout.marginWidth = MARGIN;
		gridLayout.marginHeight = MARGIN;
		gridLayout.verticalSpacing = MARGIN / 2;
		container.setLayout(gridLayout);
		container.setLayoutData(UIHelper.fillBoth());

		/**
		 * Bagian username.
		 */
		createUsername(container);

		/**
		 * Bagian password.
		 */
		createPassword(container);

		UIHelper.separator(composite, SWT.HORIZONTAL);
		return composite;
	}

	@Override
	protected Point getInitialSize() {
		return new Point(convertHorizontalDLUsToPixels(WIDTH),
				convertVerticalDLUsToPixels(HEIGHT));
	}

}
